import json
import time
from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect
from rest_framework.views import APIView
from rest_framework.response import Response
from .sers import *
import redis
from dwebsocket import accept_websocket
import socket
from bus.settings import ratekey


class Register(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        name = request.data.get('name')
        idcard = request.data.get('idcard')
        address = request.data.get('address')

        UserModel.objects.create(username=username, password=password, name=name, idcard=idcard, address=address)
        return Response({'msg': {'注册成功'}, 'code': 200})


class Login(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = UserModel.objects.filter(username=username).first()
        if user:
            if password == user.password:
                return Response({'msg': '登陆成功',
                                 'code': 200,
                                 'username': user.username,
                                 'uid': user.id})
            else:
                return Response({'msg': '用户名或者密码错误', 'code': 400})
        else:
            return Response({'msg': '用户名或者密码错误', 'code': 400})


class GetOnLines(APIView):
    def get(self, request):
        r = redis.Redis(host='localhost')
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            ip = request.META.get('HTTP_X_FOGWARDED_FOR')

        else:
            ip = request.META.get('REMOTE_ADDR')

        if r.scard('set_ip'):
            print(r.scard('set_ip'))
            r.sadd('set_ip', ip)
        else:
            r.sadd('set_ip', ip)
            r.expire('set_ip', 30)

        return Response({'online': r.scard('set_ip')})


# 实时刷新在线人数统计
@accept_websocket
def CensusGet(request):
    # 获取本机电脑名
    myname = socket.getfqdn(socket.gethostname())
    # 获取本机ip
    myaddr = socket.gethostbyname(myname)

    # 连接Redis
    r = redis.Redis()

    if request.is_websocket():
        while True:
            # 判断该数据是否存在
            if r.scard("set_ip"):
                # 向集合内添加数据
                r.sadd("set_ip", str(myaddr))
            else:
                r.sadd("set_ip", str(myaddr))
                # 设置过期时间
                r.expire("set_ip", 300)

            my_len = r.scard("set_ip")
            request.websocket.send(json.dumps(my_len))
            # 设置休眠时间
            time.sleep(7)


import pymongo
import requests
from datetime import datetime
import datetime


# 历史货币汇率
def Rate(request):
    url = "http://www.chinamoney.com.cn/ags/ms/cm-u-bk-ccpr/CcprHisNew?startDate=2021-03-07&endDate=2021-04-07&currency=USD/CNY&pageNum=1&pageSize=30"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                      '(KHTML, like Gecko) Chrome/91.0.4455.2 Safari/537.36'
    }
    response = requests.get(url=url, headers=headers)

    result = eval(response.text).get('records')

    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient['rate']
    rate = mydb['exchange']

    # //添加数据到mongo
    # for i in result:
    #     date = i.get('date')
    #     exchange = eval(i.get('values')[0])
    #     rate.insert_one({'汇率':exchange,'日期':date})

    # 获取当前时间的前七天的时间
    # 获取当前时间
    my_date = datetime.datetime.now()
    # 计算偏移天数
    offset = datetime.timedelta(days=-6)
    # 得到你想要的日期时间
    re_date = (my_date + offset).strftime('%Y-%m-%d')
    re_date = datetime.datetime.strptime(re_date, '%Y-%m-%d')

    ratelist = []
    datelist = []

    # 获取Mongo中的所有数据
    for i in rate.find():
        date = datetime.datetime.strptime(i['日期'], '%Y-%m-%d')
        # 判断大于第七天日期的数据
        if re_date <= date:
            print(i)
            datelist.insert(0, i['日期'])
            ratelist.insert(0, i['汇率'])
    print(ratelist, datelist)

    return HttpResponse(json.dumps({"ratelist": ratelist, "datelist": datelist}, ensure_ascii=False),
                        content_type="application/json")


# 实时货币汇率


# PayPal支付
import paypalrestsdk
from bus.settings import PayPalclient_id, PayPalclient_secret


def payment(request):
    paypalrestsdk.configure({
        "mode": "sandbox",  # sandbox代表沙盒
        "client_id": PayPalclient_id,
        "client_secret": PayPalclient_secret})

    payment = paypalrestsdk.Payment({
        "intent": "sale",
        "payer": {
            "payment_method": "paypal"},
        "redirect_urls": {
            "return_url": "http://localhost:8000/user/pay_execute/",  # 支付成功跳转页面
            "cancel_url": "http://localhost:3000/paypal/cancel/"},  # 取消支付页面
        "transactions": [{
            "amount": {
                "total": "1000000",
                "currency": "USD"},
            "description": "巴黎世家丝袜"}]})

    if payment.create():
        print("Payment created successfully")
        for link in payment.links:
            if link.rel == "approval_url":
                approval_url = str(link.href)
                print("Redirect for approval: %s" % (approval_url))
                return redirect(approval_url)
    else:
        print(payment.error)
        return HttpResponse("支付失败")


def testlock(request):
    res = User.objects.get(pk=1)

    if res.num > 0:
        time.sleep(5)
        # with connection.cursor() as c:
        #     c.execute(' update user set num = num - 1 where id = 1 ')
        # return HttpResponse('ok')
        # res.num = res.num - 1
        User.objects.filter(pk=1).update(num = res.num - 1)
        return HttpResponse('ok')
    else:
        return HttpResponse('钱包为空')










